#pragma once

#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <cerrno>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>


#define _Info 0
#define _Debug 1
#define _Warning 2
#define _Error 3
#define _Fatal 4
#define SIZE 1024

#define Screen 1
#define Onefile 2
#define Classfile 3

#define LogFile "log.txt"

class Log
{
public:
    Log()
    {
        printmethod = Screen;
        path = "./log/";
    }
    void Enable(int method)
    {
        printmethod = method;
    }
    std::string leveltostring(int level)
    {
        switch (level)
        {
        case _Info:
            return "Info";
        case _Debug:
            return "Debug";
        case _Warning:
            return "Warning";
        case _Error:
            return "Error";
        case _Fatal:
            return "Fatal";
        default:
            return "None";
        }
    }

    void printlog(int level, const std::string &logtxt)
    {
       
        switch (printmethod)
        {
        case Screen:
            std::cout << logtxt << std::endl;
            break;
        case Onefile:
            printOnefile(LogFile, logtxt);
            break;
        case Classfile:
            printClassfile(level, logtxt);
            break;
        default:
            break;
        }
    }
    void printOnefile(const std::string &filename,const  std::string &logtxt)
    {
        std::string logname = path + filename;
        int fd = open(logname.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666); // log.txt
        if (fd < 0)
            return;
        write(fd, logtxt.c_str(), logtxt.size());
        close(fd);
    }
    void printClassfile(int level, const std::string &logtxt)
    {
        std::string filename = LogFile;
        filename += ".";
        filename += leveltostring(level); // log.txt.Fatal
        // 复用一下上面的printonefile
        printOnefile(filename, logtxt);
    }
    ~Log() {}

    void operator()(int level, const char *format, ...)
    {
        time_t t = time(nullptr);
        struct tm *ctime = localtime(&t);
        char leftbuffer[SIZE];

        snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d]",
                 leveltostring(level).c_str(), ctime->tm_year + 1900, ctime->tm_mon + 1,
                 ctime->tm_mday, ctime->tm_hour,
                 ctime->tm_min, ctime->tm_sec);

        char rightbuffer[SIZE];
        va_list s;
        va_start(s, format);
        vsnprintf(rightbuffer, sizeof(rightbuffer), format, s);
        va_end(s);

        char logtxt[SIZE * 2];
        snprintf(logtxt, sizeof(logtxt), "%s %s", leftbuffer, rightbuffer);

        printlog(level, logtxt);
    }

private:
    int printmethod;
    std::string path;

    std::string file_name = __FILE__;  // 存储文件名
    int line_number = __LINE__;  // 存储行号
};

Log lg;



